const fs = require('fs')
const path = require('path')
const minimist = require('minimist') // 命令行解析

// 命令行参数
const argv = minimist(process.argv.slice(2), {
  default: {
    env: process.env.NODE_ENV || 'production',
  },
})

const watch = argv.w || argv.watch

const command = [
  // { src: path.join(__dirname, `../controller/api`), dist: `../public/apidoc`, url: 'http://127.0.0.1:7001/apidoc/index.html' }
  { src: path.join(__dirname, `../controller/screen`), dist: `../public/screen/apidoc`, url: 'http://127.0.0.1:7001/screen/apidoc/index.html' },
]

command.forEach((item) => {
  const { src, dist } = item
  const task = async () => {
    if (item.run) {
      console.log('[Command] skip')
      return
    }

    item.run = true

    // apidoc(src, dist)
    apidocCli(src, dist)

    console.log('[command] End')

    item.run = false
  }

  task()

  if (watch) {
    console.log('[watch] Dir', src)
    fs.watch(src, (event, filename) => {
      if (filename && event === 'change') {
        // console.log(`${filename} file Changed`)
        console.log('[watch] Filename', filename)
        task()
      }
    })
  }
})

async function apidocCli(src, dist) {
  const execShPromise = require('exec-sh').promise

  const command = `npx apidoc -i ${src} -o ${dist} --debug`
  console.log('[command] Run:', command)
  try {
    out = await execShPromise(command, true)
  } catch (e) {
    console.log('Error: ', e)
    console.log('Stderr: ', e.stderr)
    console.log('Stdout: ', e.stdout)

    return e
  }
}

function apidoc(src, dist) {
  console.log('apidoc', src, dist)
  const { createDoc } = require('apidoc')
  const doc = createDoc({
    src,
    dest: dist, // can be omitted if dryRun is true
    // if you don't want to generate the output files:
    // dryRun: true,
    // if you don't want to see any log output:
    silent: true,
  })

  // if (typeof doc !== 'boolean') {
  //   // Documentation was generated!
  //   console.log(doc.data) // the parsed api documentation object
  //   console.log(doc.project) // the project information
  // }
}
